package com.zenitera.bigdata.state;

import com.zenitera.bigdata.bean.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.AggregatingState;
import org.apache.flink.api.common.state.AggregatingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * AggregateState
 */
public class Flink02_State_Key_AggregateState {
    public static void main(String[] args) throws Exception {

        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);


        env
                .socketTextStream("localhost", 6666)
                .map(line -> {
                    String[] data = line.split(",");
                    return new WaterSensor(
                            data[0],
                            Long.valueOf(data[1]),
                            Integer.valueOf(data[2])
                    );
                })
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {


                    private AggregatingState<WaterSensor, Double> vcAvgState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        vcAvgState = getRuntimeContext().getAggregatingState(
                                new AggregatingStateDescriptor<WaterSensor, Avg, Double>(
                                        "vcAvgState",
                                        new AggregateFunction<WaterSensor, Avg, Double>() {
                                            @Override
                                            public Avg createAccumulator() {
                                                return new Avg();
                                            }

                                            @Override
                                            public Avg add(WaterSensor value, Avg acc) {
                                                acc.sum += value.getVc();
                                                acc.count++;
                                                return acc;
                                            }

                                            @Override
                                            public Double getResult(Avg acc) {
                                                return acc.avg();
                                            }

                                            @Override
                                            public Avg merge(Avg a, Avg b) {
                                                return null;
                                            }
                                        },
                                        Avg.class
                                )
                        );
                    }

                    @Override
                    public void processElement(WaterSensor value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {
                        vcAvgState.add(value);


                        out.collect(ctx.getCurrentKey() + " avg: " + vcAvgState.get());

                    }
                })
                .print();


        env.execute();
    }


    public static class Avg {
        public Integer sum = 0;
        public Long count = 0L;

        public Double avg() {

            return sum * 1.0 / count;
        }
    }
}
/*
D:\netcat-win32-1.12>nc64.exe -lp 6666
s1,1,2
s1,1,4
s1,1,12
s1,1,40
--------------------------
s1 avg: 2.0
s1 avg: 3.0
s1 avg: 6.0
s1 avg: 14.5
 */